package com.ruolin.micro.gateway.server.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author
 */

public class ResponseUtils {
    private ResponseUtils() {
    }

    public static void returnJson(HttpServletResponse response, Object responseValue) {
        Object result = null;
        if (responseValue instanceof Map) {
            Map<?, ?> responseMap = (Map<?, ?>) responseValue;

            if (responseMap.containsKey("class")) {
                responseMap.remove("class");
            }
            result = JSONObject.parseObject(JSON.toJSONString(responseMap));
        } else {
            result = responseValue;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
//          HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
//          writer = responseWrapper.getWriter();
//          writer .write(result.toString());
//          writer.flush();
//          writer.close();
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(result.toString().getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
